<template>
  <section class="room">
    <div v-show="videoStatus" class="scrollbar">
      <live-pusher :class="{big:currentVideo===-1,small:currentVideo!==-1,'no-user':userStreamList.length===0,'one-user':userStreamList.length===1}" @click="changeStyle(-1)"></live-pusher>
      <live-player :class="{small:currentVideo!==index,big:currentVideo===index,'one-user':userStreamList.length===1}" @click="changeStyle(index)"  v-for="(item,index) in userStreamList" :key="item.id" :id="item.id" :streamInfo="item"></live-player>
    </div>
    <div v-show="!videoStatus" class="start-video">
      <div class="start-video-content">
        <img class="start-video-img" src="./components/assets/live-start.png" alt="">
        <button class="start-video-btn" @click="startVideo">开始视频</button>
      </div>
    </div>
    <div class="video-control">
      <div class="control-left">
        <button class="mic" :class="{unmic:micStatus===1}" @click="micChange"></button>
        <button class="camera" :class="{uncamera:cameraStatus===1}" @click="cameraChange"></button>
        <button>{{videoTime}}</button>
      </div>
      <div class="control-right">
        <button class="close-btn" @click="closeVideo">结束视频</button>
      </div>
    </div>
  </section>
</template>

<script>
import LivePlayer from './components/live-player.vue'
import LivePusher from './components/live-pusher.vue'
import imClient from './components/utils/im-client.js'
import trtcClient from './components/utils/trtc-client.js'
import { genTestUserSig } from '../../../public/debug/GenerateTestUserSig.js'
import { randomUserID } from './components/utils/common.js'
export default {
  components: {
    LivePlayer,
    LivePusher
  },
  data () {
    return {
      currentVideo: -1,
      videoTime: '00:00:00',
      timer: null,
      initStatus: false,
      videoStatus: false,
      micStatus: 0,
      cameraStatus: 0
    }
  },
  mounted () {
    this.init()
    this.trtcClientEvent()
  },
  methods: {
    /**
     * @author ZhenYuTsai
     * @description 初始化实时音视频和IM即时通讯
     * @lastEditors ZhenYuTsai
     */
    async init () {
      this.initStatus = false
      const userID = randomUserID()
      const roomID = 123456
      const { sdkAppID, userSig } = genTestUserSig(userID)
      await imClient.init({ SDKAppID: sdkAppID })
      await imClient.login({ userID, userSig })
      await imClient.joinGroup(roomID)
      await imClient.updateMyProfile({ nick: '坐席' })
      await trtcClient.init({ sdkAppId: sdkAppID, userId: userID, userSig: userSig, roomId: roomID })
      this.initStatus = true
    },
    /**
     * @author ZhenYuTsai
     * @description 开始视频按钮点击事件
     * @lastEditors ZhenYuTsai
     */
    async startVideo () {
      if (this.initStatus) {
        await trtcClient.join()
        trtcClient.publish()
        trtcClient.playLocalStream()
        this.startTime('start')
        this.videoStatus = true
      } else {
        console.warn('请视频和通信组件初始化完成后，在开启视频！')
      }
    },
    /**
     * @author ZhenYuTsai
     * @description 关闭视频按钮点击事件
     * @lastEditors ZhenYuTsai
     */
    async closeVideo () {
      if (!this.videoStatus) return
      this.videoStatus = false
      await imClient.sendCustomMessage({ description: 'CloseVideo', data: JSON.stringify({ msg: '关闭视频' }) })
      clearInterval(this.timer)
      await imClient.quitGroup()
      await imClient.destroy()
      await trtcClient.leave()
      this.startTime('close')
      this.init()
    },
    /**
     * @author ZhenYuTsai
     * @description 点击客户视频切换样式
     * @lastEditors ZhenYuTsai
     * @param {Number} val
     */
    changeStyle (val) {
      if (this.userStreamList.length === 0 || this.userStreamList.length === 1) return
      this.currentVideo = val
    },
    /**
     * @author ZhenYuTsai
     * @description 视频时长计时器
     * @lastEditors ZhenYuTsai
     * @param {String} type
     */
    startTime (type = 'start') {
      let seconds = 0
      let minutes = 0
      let hours = 0
      if (type === 'start') {
        this.timer = setInterval(() => {
          seconds += 1
          if (seconds >= 60) {
            seconds = 0
            minutes = minutes + 1
          }

          if (minutes >= 60) {
            minutes = 0
            hours = hours + 1
          }
          const time = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
          this.videoTime = time
        }, 1000)
      } else {
        seconds = 0
        minutes = 0
        hours = 0
        clearInterval(this.timer)
        this.videoTime = '00:00:00'
      }
    },
    /**
     * @author ZhenYuTsai
     * @description 切换麦克风状态
     * @lastEditors ZhenYuTsai
     */
    micChange () {
      if (!this.videoStatus) return
      if (this.micStatus === 0) {
        this.micStatus = 1
        trtcClient.muteLocalAudio()
      } else if (this.micStatus === 1) {
        this.micStatus = 0
        trtcClient.unmuteLocalAudio()
      }
    },
    /**
     * @author ZhenYuTsai
     * @description 切换摄像头状态
     * @lastEditors ZhenYuTsai
     */
    cameraChange () {
      if (!this.videoStatus) return
      if (this.cameraStatus === 0) {
        this.cameraStatus = 1
        trtcClient.muteLocalVideo()
      } else if (this.cameraStatus === 1) {
        this.cameraStatus = 0
        trtcClient.unmuteLocalVideo()
      }
    },

    /**
     * @author ZhenYuTsai
     * @description trtcClient回调函数
     * @return {*}
     * @lastEditors ZhenYuTsai
     */
    trtcClientEvent () {
      trtcClient.$on('MIX_VIDEO', ({ localStream, remoteStreams }) => {
      // 在这里调用后台混流接口 localStream本地流、remoteStreams远端流数组
        console.log('监听混流回调', localStream, remoteStreams)
      })
      trtcClient.$on('CANCEL_MIX_VIDEO', ({ localStream, remoteStreams }) => {
      // 在这里调用后台取消混流接口 localStream本地流、remoteStreams远端流数组
        console.log('监听取消混流回调', localStream, remoteStreams)
      })
    }
  },
  computed: {
    userStreamList () {
      return trtcClient.remoteStreams
    }
  },
  async beforeDestroy () {
    trtcClient.$off('MIX_VIDEO')
    trtcClient.$off('CANCEL_MIX_VIDEO')
    clearInterval(this.timer)
    await imClient.quitGroup()
    imClient.logout()
    imClient.destroy()
    trtcClient.leave()
  }
}
</script>

<style>
.room{
  width: 800px;
  height: 620px;
  position: relative;
}
.room .scrollbar{
  overflow-y: auto;
  height: calc(100% - 50px);
  width: 100%;
}
.room .video-control{
  height: 50px;
  width: 100%;
  background-color: #111111;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.room .video-control .control-left{
  display: flex;
  align-items: center;
}
.room .video-control button{
  outline: none;
  border: none;
  background-color: transparent;
  color: #fff;
  cursor: pointer;
  margin: 0 10px;
  height: 30px;
  line-height: 30px;
}
.video-control .control-left .mic
{
  width: 20px;
  height: 30px;
  background: url('./components/assets/mic.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .mic:hover{
  background: url('./components/assets/mic-hover.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .unmic{
  background: url('./components/assets/mic-off.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .unmic:hover{
  background: url('./components/assets/mic-off-hover.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .camera{
  width: 20px;
  height: 30px;
  background: url('./components/assets/camera.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .camera:hover{
  background: url('./components/assets/camera-hover.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .uncamera{
  background: url('./components/assets/camera-off.png') 50% no-repeat;
  background-size: contain;
}
.video-control .control-left .uncamera:hover{
  background: url('./components/assets/camera-off-hover.png') 50% no-repeat;
  background-size: contain;
}

.room .video-control .control-right{
  display: flex;
  align-items: center;
}
.video-control .control-right .close-btn{
  background-color: #1890ff;
  padding: 0 15px;
  border-radius: 3px;
}
.room .start-video{
  width: 100%;
  height:  calc(100% - 50px);
  background-color: #333333;
  display: flex;
  justify-content: center;
  align-items: center;
}
.room .start-video-img{
  width: 200px;
}
.room .start-video-btn{
  outline: none;
  border: none;
  display: block;
  width: 140px;
  height: 40px;
  margin:  10px auto 0;
  color: #fff;
  background-color: #1890ff;
  border-radius: 20px;
  cursor: pointer;
}
/*滚动条样式*/
.room .scrollbar::-webkit-scrollbar {
    width: 4px;
    /*height: 4px;*/
}
.room .scrollbar::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    background: rgba(0,0,0,0.2);
}
.room .scrollbar::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    border-radius: 0;
    background: rgba(0,0,0,0.1);
}
.room .big{
  position: absolute;
  top: 0;
  left: 0;
  width: 70%;
  height: calc(100% - 50px);
}
.room .big > div{
  width: 100%;
  height: 100%;
}
.room .small{
  width: 100%;
  height: 50%;
}
.room .small > div{
  width: 30%;
  height: 100%;
  float: right;
}
.room .no-user{
  width: 100%;
  height: calc(100% - 50px);
}
.room .big.one-user{
  width: 50%;
  height: calc(100% - 50px);
}
.room .small.one-user{
  height: 100%;
}
.room .small.one-user>div{
  width: 50%;
}
</style>
